import http from '@/utils/http'
import KeyboardAudio from '@/utils/keyboardAudio'

export const vocabularyPracticeMixin = {
  data() {
    return {
      lesson: null,
      vocabularyList: [],
      currentSentenceIndex: 0,
      currentVocabularyIndex: 0,
      loading: true,
      error: null,
      userSpelling: '',
      spellingResult: null,
      userChoice: null,
      choiceResult: null,
      choices: [],
      audioLoading: false,
      audio: null,
      currentAudioUrl: null,
      errorMessage: null
    }
  },

  computed: {
    currentVocabulary() {
      if (!this.vocabularyList.length) {
        return {}
      }
      return this.vocabularyList[this.currentVocabularyIndex] || {}
    },

    currentSentence() {
      if (!this.lesson || !this.lesson.content || this.lesson.content.length === 0) {
        return { english: '', chinese: '' }
      }
      return this.lesson.content[this.currentSentenceIndex] || { english: '', chinese: '' }
    }
  },

  watch: {
    currentSentenceIndex: {
      handler() {
        this.currentVocabularyIndex = 0
        this.extractVocabularyFromLesson()
      }
    }
  },

  async mounted() {
    KeyboardAudio.register('Enter', this.togglePlayback)
    // 注册空格键
    KeyboardAudio.register(' ', this.togglePlayback)
    KeyboardAudio.register('ArrowLeft', this.playPrevious)
    KeyboardAudio.register('ArrowRight', this.playNext)
    const lessonId = this.$route.params.id
    const coursePath = this.$route.params.coursePath
    await this.loadLesson(lessonId, coursePath)
  },

  methods: {
    async loadLesson(lessonId, coursePath) {
      try {
        // Load lesson details
        const lessonResponse = await http.get(`/lessons/${coursePath}/${lessonId}`)
        this.lesson = lessonResponse

        // Extract vocabulary from lesson content
        await this.extractVocabularyFromLesson()

        // Generate choices for the first vocabulary item
        if (this.vocabularyList.length > 0) {
          this.generateChoices()
        }

        this.loading = false
      } catch (err) {
        this.error = '加载课程内容失败'
        this.loading = false
        console.error('Error loading lesson:', err)
      }
    },

    async extractVocabularyFromLesson() {
      try {
        // 获取字典中的所有单词
        const dictResponse = await http.get('/vocabulary/dictionary')
        const dictWords = dictResponse

        // 从当前句子中提取单词
        const lessonWords = new Set()
        if (this.lesson && this.lesson.content && this.lesson.content[this.currentSentenceIndex]) {
          const currentSentence = this.lesson.content[this.currentSentenceIndex]
          // 提取句子中的单词（简单按空格分割，实际应用中可能需要更复杂的处理）
          const words = currentSentence.english.split(/\s+/)
          words.forEach((word) => {
            // 移除标点符号并转换为小写
            const cleanWord = word.replace(/[^\w]/g, '').toLowerCase()
            if (cleanWord.length > 3) {
              // 只考虑长度大于3的单词
              lessonWords.add(cleanWord)
            }
          })
        }

        // 查找课程中的单词是否在字典中存在
        const matchingWords = Array.from(lessonWords)
          .filter((word) => dictWords.includes(word))
          .slice(0, 10) // 限制为最多10个单词

        // 获取这些单词的详细信息
        if (matchingWords.length > 0) {
          const promises = matchingWords.map((word) => http.get(`/vocabulary/word/${word}`))
          const results = await Promise.all(promises)
          this.vocabularyList = results.map((res) => res)
        } else {
          // 如果没有找到匹配的单词，则从字典中随机选择一些
          const sampleWords = dictWords.slice(0, 10)
          const promises = sampleWords.map((word) => http.get(`/vocabulary/word/${word}`))
          const results = await Promise.all(promises)
          this.vocabularyList = results.map((res) => res)
        }

        // 重置练习状态
        this.resetExercise()
      } catch (err) {
        this.errorMessage = '提取词汇失败'
        console.error('Error extracting vocabulary:', err)
      }
    },

    generateChoices() {
      // 为当前词汇生成选择题选项
      if (!this.currentVocabulary.meanings || !this.currentVocabulary.meanings.length) {
        this.choices = ['无可用选项']
        return
      }

      // 获取当前词汇的正确释义
      const correctMeaning = this.currentVocabulary.meanings[0].explanations[0] || '默认释义'

      // 从其他词汇中获取干扰项
      const distractors = []
      for (let i = 0; i < this.vocabularyList.length && distractors.length < 3; i++) {
        if (
          i !== this.currentVocabularyIndex &&
          this.vocabularyList[i].meanings &&
          this.vocabularyList[i].meanings.length
        ) {
          const explanation = this.vocabularyList[i].meanings[0].explanations[0]
          if (explanation && !distractors.includes(explanation)) {
            distractors.push(explanation)
          }
        }
      }
      const defaultDistractors = [
        '美丽的',
        '漂亮的',
        '大方',
        '小区',
        '高尚',
        '堂堂',
        '教师',
        '端庄大方的',
        '柏树',
        '损失',
        '高高在上的',
        '河边',
        '特制',
        '性格，性格上的'
      ]
      // 确保有足够选项
      while (distractors.length < 3) {
        // 随机从默认干扰项中选择3项放入distractors
        for (let i = 0; i < 3; i++) {
          const idx = Math.floor(Math.random() * defaultDistractors.length)
          distractors.push(defaultDistractors[idx])
          defaultDistractors.splice(idx, 1)
        }
      }

      // 组合选项并随机排序
      this.choices = [correctMeaning, ...distractors]
      this.shuffleArray(this.choices)
    },

    shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[array[i], array[j]] = [array[j], array[i]]
      }
    },

    async playPronunciation() {
      if (!this.currentVocabulary.word) return

      // 如果屏幕是小尺寸，不设置this.audioLoading，则不会显示加载提示
      if (window.innerWidth < 768) {
        this.audioLoading = false
      } else {
        this.audioLoading = true
      }

      try {
        // 获取音频文件(base64编码)
        const audioResponse = await http.get(`/vocabulary/pronunciation/${this.currentVocabulary.word}`)

        // 将base64编码转换为blob
        const byteCharacters = atob(audioResponse)
        const byteNumbers = new Array(byteCharacters.length)
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i)
        }
        const byteArray = new Uint8Array(byteNumbers)
        // 尝试多种音频格式
        let blob = new Blob([byteArray], { type: 'audio/wav' })
        let audioUrl = URL.createObjectURL(blob)

        // 检查URL是否有效
        if (!audioUrl) {
          throw new Error('无法创建音频URL')
        }

        if (this.audio) {
          this.audio.pause()
          this.audio = null
        }

        this.audio = new Audio(audioUrl)

        // 添加错误处理
        this.audio.onerror = (e) => {
          console.error('Audio playback error:', e)
          // 尝试其他格式
          try {
            URL.revokeObjectURL(audioUrl)
            blob = new Blob([byteArray], { type: 'audio/mpeg' })
            audioUrl = URL.createObjectURL(blob)
            this.audio = new Audio(audioUrl)
            this.audio.play()
          } catch (retryError) {
            this.errorMessage = `播放发音时出错: 音频格式不支持或文件损坏`
          }
        }

        // 添加canplay事件监听
        this.audio.oncanplay = () => {
          // console.log('Audio can play');
        }

        await this.audio.play()

        this.audio.onended = () => {
          URL.revokeObjectURL(audioUrl)
          this.audio = null
        }
      } catch (error) {
        console.error('Error playing pronunciation:', error)
        if (error.response && error.response.status === 404) {
          this.errorMessage = `未找到单词 "${this.currentVocabulary.word}" 的发音文件`
        } else {
          this.errorMessage = `播放发音时出错: ${error.message}`
        }
      } finally {
        this.audioLoading = false
      }
    },

    showAnswer() {
      this.userSpelling = this.currentVocabulary.word
      this.spellingResult = true

      // 找到正确答案的索引
      if (this.currentVocabulary.meanings && this.currentVocabulary.meanings.length) {
        const correctMeaning = this.currentVocabulary.meanings[0].explanations[0]
        const correctIndex = this.choices.findIndex((choice) => choice === correctMeaning)
        if (correctIndex !== -1) {
          this.userChoice = correctIndex
          this.choiceResult = true
        }
      }
    },

    nextVocabulary() {
      if (this.vocabularyList.length > 0) {
        this.currentVocabularyIndex = (this.currentVocabularyIndex + 1) % this.vocabularyList.length
        this.resetExercise()
      }
    },

    resetExercise() {
      this.userSpelling = ''
      this.spellingResult = null
      this.userChoice = null
      this.choiceResult = null
      this.generateChoices()
      // 停止音频播放
      if (this.audio) {
        this.audio.pause()
        this.audio = null
      }
    },

    checkSpelling() {
      if (!this.currentVocabulary.word) return

      const isCorrect = this.userSpelling.trim().toLowerCase() === this.currentVocabulary.word.toLowerCase()
      this.spellingResult = isCorrect
    },

    checkChoice() {
      if (this.userChoice === null) return

      // 找到正确答案的索引
      if (this.currentVocabulary.meanings && this.currentVocabulary.meanings.length) {
        const correctMeaning = this.currentVocabulary.meanings[0].explanations[0]
        const correctIndex = this.choices.findIndex((choice) => choice === correctMeaning)
        this.choiceResult = this.userChoice === correctIndex
      }
    }
  },

  beforeUnmount() {
    KeyboardAudio.destroy()
    // 组件销毁前停止音频播放
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }
  }
}
